package com.ymzwl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;

public class Test {
	static Configuration conf = new Configuration(true);

	/**
	 * @param fName /fName 文件夹名字和路径
	 */
	public static void create(String fName) {
		try {
			FileSystem fs = FileSystem.get(conf);
			Path ifile = new Path(fName);
			if (fs.exists(ifile)) {
				fs.delete(ifile, true);
			}
			fs.mkdirs(ifile);
			fs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void upload(String fPath) {
		try {
			FileSystem fs = FileSystem.get(conf);
			Path path = new Path(fPath);
			FSDataOutputStream out=fs.create(path);
			InputStream input=new BufferedInputStream(new FileInputStream(new File("c:\\test.txt")));
			IOUtils.copyBytes(input, out, conf,true);
			out.close();
			input.close();
			fs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void getBlockInfo(String fPath) {
		try {
			FileSystem fs = FileSystem.get(conf);
			Path path = new Path(fPath);
			FileStatus fStatus=fs.getFileStatus(path);
			BlockLocation[] bls=fs.getFileBlockLocations(fStatus, 0, fStatus.getLen());
			for (BlockLocation b:bls) {
				System.out.println("BlockLocation:"+b);
			}
			fs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		//create("/test");
		//upload("/test/test.txt");
		//getBlockInfo("/test/test.txt");
		getBlockInfo("/user/root/test.txt");
		
		/*
		BlockLocation:0,1048576,node172,node173
		BlockLocation:1048576,740314,node172,node173
		输出解释
		1 偏移量
		2 块实际大小（字节数）
		3 4 位置信息
		*/
		
		
	}
}
